package xyz.hzxiao.handler.init;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.hzxiao.client.ClientChannelHolder;

/**
 * WebSocket通道连接断开处理器
 *
 * @author ：FuXx
 * @className : xyz.hzxiao.handler.init.WebSocketServerChannelHandler
 * @since ：2025/1/10
 */
public class WebSocketServerChannelHandler extends ChannelInboundHandlerAdapter {


    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServerChannelHandler.class);

    /**
     * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward
     * to the next {@code ChannelInboundHandler} in the {@code ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx the {@code ChannelHandlerContext} which this {@code SimpleChannelInboundHandler}
     * @param msg the message to handle
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
///        if (msg instanceof FullHttpRequest request) {
//            this.fullHttpRequestHandler(ctx, request);
//            this.isFullHttpRequest = Boolean.TRUE;
//        }
        super.channelRead(ctx, msg);
    }

    /**
     * Calls {@link ChannelHandlerContext#fireChannelReadComplete()} to forward
     * to the next {@code ChannelInboundHandler} in the {@code ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx the {@code ChannelHandlerContext} which this {@code SimpleChannelInboundHandler}
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
///        while (this.isFullHttpRequest) {
//            this.isFullHttpRequest = Boolean.FALSE;
//        }
        super.channelReadComplete(ctx);
        ctx.flush();
    }

    /**
     * @param ctx     the {@code ChannelHandlerContext} which this {@code SimpleChannelInboundHandler}
     * @param request http请求
     */
    private void fullHttpRequestHandler(ChannelHandlerContext ctx, FullHttpRequest request) {
        String uri = request.uri();
        String roomNo = uri.substring(uri.lastIndexOf('/') + 1);
        String replace = uri.replace(roomNo, "");
        Channel channel = ctx.channel();
        ClientChannelHolder.addClient(channel, roomNo);
        channel.attr(AttributeKey.valueOf("roomNo")).set(roomNo);
        request.setUri(replace);
    }

    /**
     * Calls {@link ChannelHandlerContext#fireChannelInactive()} to forward
     * to the next {@code ChannelInboundHandler} in the {@code ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx the {@code ChannelHandlerContext} which this {@code SimpleChannelInboundHandler}
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        clearClient(ctx);
    }

    /**
     * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward
     * to the next {@code ChannelHandler} in the {@code ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx   the {@code ChannelHandlerContext} which this {@code SimpleChannelInboundHandler}
     * @param cause the cause of the failed operation
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        clearClient(ctx);
    }

    /**
     * 清除客户端信息
     *
     * @param ctx the {@code ChannelHandlerContext} which this {@code SimpleChannelInboundHandler}
     */
    private void clearClient(ChannelHandlerContext ctx) {
        String channelId = ctx.channel().id().asShortText();
        ClientChannelHolder.removeClient(channelId);
        ctx.flush();
        ctx.close();
    }
}
